package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.PublicAccess;
import com.yhh.college_information_platform.annotation.RequireAuth;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.dto.*;
import com.yhh.college_information_platform.service.UserService;
import com.yhh.college_information_platform.vo.LoginVO;
import com.yhh.college_information_platform.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户Controller
 *
 * @author yhh
 * @date 2025-10-05
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册（游客可访问）
     */
    @PublicAccess
    @PostMapping("/register")
    public Result<Void> register(@Validated @RequestBody UserRegisterDTO registerDTO) {
        userService.register(registerDTO);
        return Result.success("注册成功", null);
    }

    /**
     * 用户登录（游客可访问）
     */
    @PublicAccess
    @PostMapping("/login")
    public Result<LoginVO> login(@Validated @RequestBody UserLoginDTO loginDTO) {
        LoginVO loginVO = userService.login(loginDTO);
        return Result.success("登录成功", loginVO);
    }

    /**
     * 获取当前用户信息（需要登录）
     */
    @RequireAuth
    @GetMapping("/info")
    public Result<UserVO> getUserInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        UserVO userVO = userService.getUserInfo(userId);
        return Result.success(userVO);
    }

    /**
     * 更新用户信息（需要登录）
     */
    @RequireAuth
    @PutMapping("/update")
    public Result<Void> updateUserInfo(
            @Validated @RequestBody UserUpdateDTO updateDTO,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        userService.updateUserInfo(userId, updateDTO);
        return Result.success("更新成功", null);
    }

    /**
     * 修改密码（需要登录）
     */
    @RequireAuth
    @PutMapping("/password")
    public Result<Void> updatePassword(
            @Validated @RequestBody PasswordUpdateDTO passwordDTO,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        userService.updatePassword(userId, passwordDTO);
        return Result.success("密码修改成功", null);
    }

    /**
     * 根据学号查询用户（游客可访问）
     */
    @PublicAccess
    @GetMapping("/student/{studentId}")
    public Result<UserVO> getUserByStudentId(@PathVariable String studentId) {
        UserVO userVO = userService.getUserByStudentId(studentId);
        return Result.success(userVO);
    }

    /**
     * 上传头像（需要登录）
     */
    @RequireAuth
    @PostMapping("/avatar/upload")
    public Result<Map<String, Object>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        // 兜底：从请求头解析 token 获取 userId
        if (userId == null) {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            try {
                com.yhh.college_information_platform.utils.JwtUtil jwtUtil =
                        org.springframework.web.context.support.WebApplicationContextUtils
                                .getRequiredWebApplicationContext(request.getServletContext())
                                .getBean(com.yhh.college_information_platform.utils.JwtUtil.class);
                if (token != null && jwtUtil.validateToken(token)) {
                    userId = jwtUtil.getUserIdFromToken(token);
                }
            } catch (Exception ignore) {}
        }
        
        String avatarUrl = userService.uploadAvatar(userId, file);
        
        Map<String, Object> data = new HashMap<>();
        data.put("url", avatarUrl);
        
        return Result.success("头像上传成功", data);
    }

    /**
     * 退出登录（游客可访问，前端清除Token即可）
     */
    @PublicAccess
    @PostMapping("/logout")
    public Result<Void> logout() {
        return Result.success("退出成功", null);
    }
}
